package com.cms.login;

import com.auxiliary.Util;
import com.doman.Consumer;
import com.doman.LoginFrom;
import com.resultmsg.BaseEnums;
import com.resultmsg.Result;
import com.resultmsg.Results;
import com.server.ConsumerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = {"http://localhost:9528", "null"})
@RequestMapping(value = "/educloud")
@RestController
public class LoginController {


    @Autowired
    private ConsumerMapper mapper;

    /**
     * 表名称
     */
    public static String dbname = "consumer";

    public LoginController() {

    }

    @PostConstruct  //加上该注解表明该方法会在bean初始化后调用，以替代构造函数无法从配置文件取值
    public void init() {

    }

    @RequestMapping(value="/consumers/conditions",method = RequestMethod.POST)
    public Result usermohu(@RequestBody  Consumer consumer){
        List<Consumer> res = mapper.selectByPrimaryUserMoHu(consumer);
        if(res.size() > 0){
            return Results.successWithData(res,BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
        }else{
            return Results.failureWithData(res, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
        }
    }

    /**
     * 首页登录
     *
     * @param loginFrom
     * @return
     */
//    @RequestMapping(value = "/user/login")
    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public Map login(@RequestBody LoginFrom loginFrom) {

        HashMap<String, Object> response = new HashMap<>();
        HashMap<String, Object> responseData = new HashMap<>();

        System.out.println(loginFrom.getUsername() + "  " + loginFrom.getPassword());

        if (loginFrom.getPassword() == null || loginFrom.getUsername() == null) {
            response.put("code", "10000");
            response.put("msg", "参数异常");
            response.put("data", responseData);
            return response;
        }

       List<Consumer> res = mapper.login(loginFrom);
        int res1 = res.size();
        if (res1 > 0) {//有此用户
            Consumer consumer = res.get(0);
            if(consumer.getAlive()<=0){//判断用户是否未激活
                responseData.put("token", -1);
                response.put("code", "10000");
                response.put("msg", "用户没有登录权限");
                response.put("data", responseData);
                return response;
            }else{
                if(consumer.getAlive()>1){//判断用户是否为登录状态
                    responseData.put("token", -1);
                    response.put("code", "10000");
                    response.put("msg", "用户已登录");
                    response.put("data", responseData);
                    return response;
                }else{
                    //单点登录控制
//                   int res_updata =  mapper.updatelogin(loginFrom.getUsername());

                    int res_updata =1;
                   if(res_updata>0){//更新登录状态
                       responseData.put("token", loginFrom.getUsername() );
                       response.put("code", "20000");
                       response.put("msg", "登录成功");
                       response.put("data", responseData);
                   }else{
                       responseData.put("token", -1);
                       response.put("code", "10000");
                       response.put("msg", "登录失败");
                       response.put("data", responseData);
                   }

                }
            }
        } else {//没有用户/账号密码错误
            responseData.put("token", -1);
            response.put("code", "10000");
            response.put("msg", "用户不存在");
            response.put("data", responseData);
        }
        return response;
    }

    @CrossOrigin
    @GetMapping(value = "/user/info")
    public Map info(@RequestParam(value = "token") String token) {
        HashMap<String, Object> responseInfo = new HashMap<>();
        HashMap<String, Object> responseData = new HashMap<>();
        Consumer consumer = mapper.selectByUserName(token);
        if(consumer!=null){
            responseData.put("routes", consumer.getRoutes());
            responseData.put("roles", consumer.getRole());
            responseData.put("organize", consumer.getOrganize());
            responseData.put("name", consumer.getAccount());
            responseData.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            responseData.put("introduction", "I am a super administrator");
//        responseInfo.put(token,responseData);

            responseInfo.put("code", "20000");
            responseInfo.put("msg", "登录成功");
            responseInfo.put("data", responseData);
        }else{
            responseInfo.put("code", "11000");
            responseInfo.put("msg", "获取用户信息失败");
            responseInfo.put("data", responseData);
        }

        return responseInfo;
    }

    @RequestMapping(value = "/user/logout", method = RequestMethod.POST)
    public Result logout(@RequestBody LoginFrom loginFrom){
      int res = mapper.logout(loginFrom.getUsername());
      if(res>0){
          return Results.success(BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
      }else{
          return Results.failureWithData(res, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());

      }

    }

    /**
     * 获取管理员用户列表
     *
     * @param organize
     * @return
     */
    @RequestMapping(value = "/consumers/organize/{oType}", method = RequestMethod.GET)
    public Result getConsumersByOrganize(@PathVariable("oType") String organize) {
        HashMap<String, Object> response = new HashMap<>();
        HashMap<String, Object> responseData = new HashMap<>();
        List<Consumer> list = mapper.getConsumer(organize);
        return Results.successWithData(list, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
    }

    /**
     * 获取管理员用户列表
     *
     * @return
     */
    @RequestMapping(value = "/consumers", method = RequestMethod.GET)
    public Result getConsumers() {
        try{
            List<Consumer> list = mapper.getConsumer();
            return Results.successWithData(list, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());

        }catch (Exception e){
            return Results.failureWithData(e, BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());

        }


    }


    /**
     * 创建管理员用户
     *
     * @param consumer
     * @return
     */
    @RequestMapping(value = "/consumers", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public Result addConsumer(@RequestBody Consumer consumer) {
//用户名不能为空&不能重复
        consumer.setCreateTime(Util.getCurrentTime());
        consumer.setUpdateTime(Util.getCurrentTime());
        consumer.setAlive(1);
        try {
            int res = mapper.insert(consumer);

            if (res > 0) {//
                return Results.successWithData(consumer, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
            } else {//
                return Results.failureWithData(res, BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
            }
        } catch (Exception e) {
            return Results.failureWithData("用户名已被占用", BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
        }


    }


    @RequestMapping(value = "/consumers", method = RequestMethod.PUT)
    public Result updateConsumer(@RequestBody Consumer consumer) {

        consumer.setUpdateTime(Util.getCurrentTime());

        int res = mapper.updateByPrimaryKeySelective(consumer);
        if(res>0)
        return Results.success(BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
        else
        return Results.failure(BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
    }

    @RequestMapping(value = "/consumers/{id}", method = RequestMethod.DELETE)
    public Result delConsumer(@PathVariable int id) {

        int res = mapper.deleteByPrimaryKey(id);

        if (res > 0)
            return Results.success(BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
        else
            return Results.failure(BaseEnums.OPERATION_FAILURE.code(), BaseEnums.OPERATION_FAILURE.desc());
    }



    @RequestMapping(value = "/test")
    public Map test() {
        System.out.println("port=" + "  " + "  ");
//        return ResultUtil.success("version-1.0.1");
//        return ResultUtil.Success("version-1.0.2","");//修改了访问跟目录：61
        HashMap<String, Object> responseInfo = new HashMap<>();
        HashMap<String, Object> responseData = new HashMap<>();
        responseData.put("version", "1.0.1");
        responseInfo.put("code", 20000);
        responseInfo.put("msg", "登录成功");
        responseInfo.put("data", responseData);
        return responseInfo;
    }

}
